#include "gd32w51x.h"
#include "stdio.h"
#include "DevicesIIC.h"
#include "DevicesEEPROM.h"


#define EEPROM_DMA_MODE 0

void vEEPROMInit(void)
{
    vIIC1Init();
}

int8_t cEEPROMWriteDatas(uint16_t usAddr,  uint8_t *pucBuff, int32_t iLength)
{
    int32_t iLengthNow = 0;
    int8_t cError = 0;

    if((iLength < 0) || (pucBuff == NULL))
        return 1;

    while(iLength > 0)
    {
        /* 第一次循环，需要进行页对齐 */
        if((iLengthNow == 0) && ((usAddr % EEPROM_WRITE_PAGE_SIZE) != 0))
        {
            iLengthNow = EEPROM_WRITE_PAGE_SIZE - (usAddr % EEPROM_WRITE_PAGE_SIZE);
            iLengthNow = (iLengthNow > iLength) ? iLength : iLengthNow;
        }
        else
        {
            iLengthNow = (iLength > EEPROM_WRITE_PAGE_SIZE) ? EEPROM_WRITE_PAGE_SIZE : iLength;
        }

#if EEPROM_DMA_MODE
        if((cError = cI2CxDMAWriteDatas(I2C1, EEPROM_24C04_ADDR, usAddr, pucBuff, iLengthNow)) != 0)
#else
        if((cError = cI2CxWriteDatas(I2C1, EEPROM_24C04_ADDR, usAddr, pucBuff, iLengthNow)) != 0)
#endif
        {
            printf("cEEPROMWriteDatas cError: 0x%02X\t usAddr: %04X\n\r", cError, usAddr);
            return cError;
        }

        usAddr  += iLengthNow;
        pucBuff += iLengthNow;
        iLength -= iLengthNow;
    }

    return 0;
}

int8_t cEEPROMReadDatas(uint16_t usAddr, uint8_t *pucBuff, int32_t iLength)
{
    int32_t iLengthNow = 0;
    int8_t cError = 0;

    if((iLength < 0) || (pucBuff == NULL))
        return 1;

    while(iLength > 0)
    {
        /* 第一次循环，需要进行页对齐 */
        if((iLengthNow == 0) && ((usAddr % EEPROM_READ_PAGE_SIZE) != 0))
        {
            iLengthNow = EEPROM_READ_PAGE_SIZE - (usAddr % EEPROM_READ_PAGE_SIZE);
            iLengthNow = (iLengthNow > iLength) ? iLength : iLengthNow;
        }
        else
        {
            iLengthNow = (iLength > EEPROM_READ_PAGE_SIZE) ? EEPROM_READ_PAGE_SIZE : iLength;
        }


#if EEPROM_DMA_MODE
        if((cError = cI2CxDMAReadDatas(I2C1, EEPROM_24C04_ADDR, usAddr, pucBuff, iLengthNow)) != 0)
#else
        if((cError = cI2CxReadDatas(I2C1, EEPROM_24C04_ADDR, usAddr, pucBuff, iLengthNow)) != 0)
#endif
        {
            printf("cEEPROMReadDatas cError: 0x%02X\t usAddr: %04X\n\r", cError, usAddr);
            return cError;
        }

        usAddr  += iLengthNow;
        pucBuff += iLengthNow;
        iLength -= iLengthNow;
    }

    return 0;
}
